interface taskListArray {
  id: string,
  taskStartTime: string,
  taskName: string,
  taskCode: string,
  type: string // 普通代码common、api调用代码：api
}

export class autoProcess {
  /** 自动化流程配置 */
  private config = {
    startDateTime: '',
    endDateTime: '',
  }
  /** 自动化流程列表 */
  private taskList: taskListArray[] = []

  constructor(startDateTime: string, endDateTime: string, taskList: Array<taskListArray>) {
    this.config.startDateTime = startDateTime;
    this.config.endDateTime = endDateTime;
    this.taskList = taskList; 
  }

  /** 初始化 */
  async init() {
    this.taskList.forEach(async (e) => {
      if (e.type === 'commen') {
        if (this.config.startDateTime === 'auto') {
          this.funEval(e.taskCode)
        } else {
          // e.taskStartTime
        }
      }
      if (e.type === 'api') {
        if (this.config.startDateTime === 'auto') {
          await this.asyncHandle(this.funEval(e.taskCode))
        } else {
          // e.taskStartTime
        }
      }
    });
    return true
  }

  /** 封装promise以在async/await下处理错误信息，方便同一时间内异步处理每一个api */
  asyncHandle(promise: any) {
    if (!promise || !promise.then) {
      return new Promise((resolve, reject) => {
        reject(new Error("requires promises as the param"));
      }).catch((err) => {
        return [err, null];
      });
    }
    return promise.then(function () {
      return [null, ...arguments];
    }).catch((err: any) => {
      return [err, null];
    });
  }

  /** 代替eval方案 */
  funEval(value: string)  {
    return new Function("return " + value + ";")();
  }
}